package com.yctan.base.controller;


import com.yctan.base.entity.R;
import com.yctan.base.utils.MyException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;

public class BaseController {

    /**
     * 日志对象
     */
    protected Logger logger = LoggerFactory.getLogger(getClass());

    //处理异常范围
    @ExceptionHandler({Exception.class})
    protected Map<String, Object> handleException(Throwable e, HttpServletResponse response) {
        if(e instanceof MyException){
            return R.error(e.getMessage(), response);
        } else if(e instanceof HttpMessageNotReadableException){
            return R.error("参数格式错误", response);
        }
        logger.error("系统错误",e);
        StringWriter sw = null;
        PrintWriter pw = null;
        String message = "";
        try {
            sw = new StringWriter();
            pw = new PrintWriter(sw);
            e.printStackTrace(pw);//将出错的栈信息输出到printWriter中
            pw.flush();
            sw.flush();
            message = sw.toString().split("\n")[0];
        } catch (Exception e2) {
            e2.printStackTrace();
        } finally {
            if (sw != null) {
                try {
                    sw.close();
                } catch (IOException e3) {
                    e3.printStackTrace();
                }
            }
            if (pw != null) {
                pw.close();
            }
        }
        return R.error(message,response);
    }


    /**
     * 发送http请求
     * @param strUrl url地址
     * @param type 请求方式
     * @return 返回参数
     */
    protected String sendHttp(String strUrl, String type, Map<String,String> map) {
        HttpURLConnection con = null;
        BufferedReader buffer = null;
        StringBuffer resultBuffer = new StringBuffer();

        String parameter = buildMap(map);
        strUrl = strUrl+"?"+parameter;

        try {
            URL url = new URL(strUrl);
            //得到连接对象
            con = (HttpURLConnection) url.openConnection();
            //设置请求类型
            con.setRequestMethod(type);
            //设置请求需要返回的数据类型和字符集类型
            con.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
            //允许写出
            con.setDoOutput(true);
            //允许读入
            con.setDoInput(true);
            //不使用缓存
            con.setUseCaches(false);
            //得到响应码
            int responseCode = con.getResponseCode();

            if(responseCode == HttpURLConnection.HTTP_OK){
                //得到响应流
                InputStream inputStream = con.getInputStream();
                //将响应流转换成字符串
                resultBuffer = new StringBuffer();
                String line;
                buffer = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
                while ((line = buffer.readLine()) != null) {
                    resultBuffer.append(line);
                }
            }

        }catch(Exception e) {
            e.printStackTrace();
            return null;
        }
        return resultBuffer.toString();
    }

    /**
     * map转化为url拼接
     * @param map
     * @return
     */
    public String buildMap(Map<String, String> map) {
        StringBuffer sb = new StringBuffer();
        if (map.size() > 0) {
            for (String key : map.keySet()) {
                sb.append(key + "=");
                if (StringUtils.isEmpty(map.get(key))) {
                    sb.append("&");
                } else {
                    String value = map.get(key);
                    try {
                        value = URLEncoder.encode(value, "UTF-8");
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    sb.append(value + "&");
                }
            }
        }
        return sb.toString();
    }
}
